<template>

  <div class="app-container">

    <el-descriptions title="策略详情">
      <el-descriptions-item label="策略名称"><el-tag size="small">策略1-(50个设备)</el-tag></el-descriptions-item>
      <el-descriptions-item label="任务组数">
        <el-tag size="small">5</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="每组任务数"><el-tag size="small">10</el-tag></el-descriptions-item>
      <el-descriptions-item label="调度间隔/秒"><el-tag size="small">10</el-tag></el-descriptions-item>
    </el-descriptions>
    <div class="filter-container">
      <el-select placeholder="选择策略">
        <el-option label="策略1-(50个设备)-禁用" value="shanghai" />
        <el-option label="策略2-(10个设备)-禁用" value="beijing" />
        <el-option label="策略3-(50个设备)-启用" value="beijing" />
      </el-select>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      row-key="id"
      border
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
    <el-table-column
      prop="date"
      label="组标识"
      width="180">
    </el-table-column>
    <el-table-column
      prop="name"
      label="任务数/设备编号"
      width="180">
    </el-table-column>
    <el-table-column
      prop="address"
      label="调度间隔(秒)/地址">
    </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  addUser,
  listRole,
  listRoleByUserId,
  listUser,
  modifyUser,
  removeUser,
  saveRoleByUserId
} from '@/api/user/user-manager'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { validPassword, validPhoneNum, validUsername } from '@/utils/validate'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'UserManager',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        0: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    const generateData = _ => {
      const roles = []
      listRole({}).then(response => {
        const { data } = response
        const result = data || []
        result.forEach(item => {
          roles.push({
            key: item.id,
            label: item.roleName,
            disabled: item.id === 1
          })
        })
      })
      return roles
    }
    return {
      renderFunc(h, option) {
        return <span > { option.key } - { option.label } < /span>
      },
      value: {
        roles: [],
        userId: ''
      }, // 已选角色
      roles: generateData(), // 所有角色
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        nickName: ''
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: [{ key: '1', text: '启用' }, { key: '0', text: '禁用' }],
      showReviewer: false,
      temp: {
        id: '',
        username: '',
        nickName: '',
        phoneNum: '',
        password: '',
        status: '1'
      },
      dialogFormVisible: false,
      dialogFormVisible1: true,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '重置策略'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {},
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    load(tree, treeNode, resolve) {
      console.log(treeNode)
      setTimeout(() => {
        resolve([
          {
            id: 31,
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }, {
            id: 32,
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }
        ])
      }, 1000)
    },
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
    },
    getList() {
      this.listLoading = true
      listUser(this.listQuery).then(response => {
        this.list = [{
          id: 1,
          date: '任务组1',
          name: '5',
          address: '10',
          children: [{
            id: 31,
            date: '',
            name: '10005',
            address: '192.168.31.3:8081'
          }, {
            id: 32,
            date: '',
            name: '10006',
            address: '192.168.31.3:8081'
          }]
        }, {
          id: 2,
          date: '任务组2',
          name: '5',
          address: '3',
          children: [{
            id: 31,
            date: '',
            name: '10007',
            address: '192.168.31.3:8081'
          }, {
            id: 32,
            date: '',
            name: '10008',
            address: '192.168.31.3:8081'
          }]
        }, {
          id: 3,
          date: '任务组3',
          name: '5',
          address: '4',
          children: [{
            id: 31,
            date: '',
            name: '10009',
            address: '192.168.31.3:8081'
          }, {
            id: 32,
            date: '',
            name: '10010',
            address: '192.168.31.3:8081'
          }]
        }, {
          id: 4,
          date: '任务组4',
          name: '2',
          address: '4',
          children: [{
            id: 31,
            date: '',
            name: '10011',
            address: '192.168.31.3:8081'
          }, {
            id: 32,
            date: '',
            name: '10012',
            address: '192.168.31.3:8081'
          }]
        }]
        // this.total = response.data.total
        // Just to simulate the time of the request
        console.log('response', response)
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleDistributeRoles(row) {
      this.listLoading = true
      console.log('所有列表', this.roles)
      // 获取已选中角色列表
      listRoleByUserId({ id: row.id }).then(response => {
        const { data } = response
        const result = data || []
        const roles = []
        result.forEach(item => {
          roles.push(item.id)
        })
        this.value.roles = roles
        this.value = {
          roles: roles,
          localeId: row.id
        }
        this.listLoading = false
      })
      this.dialogStatus = 'distribute'
      this.dialogPvVisible = true
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        username: '',
        nickName: '',
        phoneNum: '',
        password: '',
        status: '1'
      }
    },
    handleCreate() {
      this.rules = {
        username: [{ required: true, trigger: ['blur', 'change'], validator: validUsername }],
        phoneNum: [{ required: false, trigger: ['blur', 'change'], validator: validPhoneNum }],
        password: [{ required: true, trigger: ['blur', 'change'], validator: validPassword }]
      }
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.phoneNum === '') {
            delete this.temp.phoneNum
          }
          addUser(this.temp).then(response => {
            const { data } = response
            this.temp.id = data.id
            this.temp.createTime = data.createTime
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 3000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.rules = {}
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          modifyUser(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.total = this.total + 1
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    confirmData(value) {
      this.listLoading = true
      saveRoleByUserId({ 'roleIds': value.roles, 'userId': value.userId }).then(() => {
        // const index = this.list.findIndex(v => v.id === this.temp.id)
        // this.list.splice(index, 1, this.temp)
        this.listLoading = false
        this.$notify({
          title: '成功',
          message: '角色分配',
          type: 'success',
          duration: 2000
        })
        this.dialogPvVisible = false
      })
    },
    handleDelete(row, index) {
      removeUser({ id: row.id }).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
